package com.jzg.jcptadmin.ui;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.StringUtils;
import com.jzg.jcptadmin.adpter.RejectAdapter;
import com.jzg.jcptadmin.app.ActivityHelp;
import com.jzg.jcptadmin.app.AppManager;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.local.LocalData;
import com.jzg.jcptadmin.data.vo.CarDetails;
import com.jzg.jcptadmin.data.vo.StatusData;
import com.jzg.jcptadmin.data.vo.SuccessData;
import com.jzg.jcptadmin.data.vo.TaskViewData;
import com.jzg.jcptadmin.presenter.OperationPresenter;
import com.jzg.jcptadmin.presenter.TaskViewPresenter;
import com.jzg.jcptadmin.viewinterface.OperationInterface;
import com.jzg.jcptadmin.viewinterface.TaskViewInterface;
import com.orhanobut.logger.Logger;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 操作中驳回、退回等界面
 * RejectActivity
 *
 * @author sunbl
 *         created at 2016/1/21 16:06
 */
public class RejectActivity extends BaseActivity implements OperationInterface, TaskViewInterface, View.OnClickListener {

    @Bind(R.id.detection_result_edit)
    EditText result;
    @Bind(R.id.count)
    TextView count;
    @Bind(R.id.title_content)
    TextView inputTopText;
    @Bind(R.id.tv_yuanyin)
    TextView tvYuanyin;
    @Bind(R.id.select_reason)
    TagFlowLayout selectReason;
    @Bind(R.id.ed_c2b)
    EditText edC2b;
    @Bind(R.id.ed_b2c)
    EditText edB2c;
    @Bind(R.id.ll_jianyijiage)
    LinearLayout llJianyijiage;
    @Bind(R.id.tv_qita)
    TextView tvQita;
    @Bind(R.id.ll_TagFlowLayout)
    LinearLayout llTagFlowLayout;
    @Bind(R.id.tv_zhushi)
    TextView tvZhushi;
    @Bind(R.id.tv_right)
    TextView tvRight;
    private OperationPresenter operationPresenter;
    private String status;
    private String id;
    private TaskViewPresenter taskViewPresenter;
    //    private List<String> list = new ArrayList<>();
    private List<String> selectReasons = new ArrayList<>();//选中的原因
    private String selectReasonStr = "";//选择的原因
    String priceReson = "";//比较价格的原因
    private List<String> reasons = new ArrayList<>();
    private StatusData statusData;
    private RejectAdapter rejectAdapter;
    private CarDetails details;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reject);
        ButterKnife.bind(this);
        inputTopText.setText("驳回原因");
        tvRight.setText("提交");
        statusData = appContext.getStatus();
        status = getIntent().getStringExtra("status");
        details = getIntent().getParcelableExtra("details");
        id = getIntent().getStringExtra("id");
        operationPresenter = new OperationPresenter(DataManager.getInstance());

        operationPresenter.attachView(this);
        //专业线下退回P层
        taskViewPresenter = new TaskViewPresenter(DataManager.getInstance());
        taskViewPresenter.attachView(this);
        initView();
        result.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                count.setText(s.length() + "/200");
            }
        });
    }

    private void initView() {
        StringUtils.priceTextWatcher(edC2b, appContext);
        StringUtils.priceTextWatcher(edB2c, appContext);
        switch (status) {
            case "退回":
                tvZhushi.setVisibility(View.VISIBLE);
                tvQita.setVisibility(View.VISIBLE);
                llJianyijiage.setVisibility(View.GONE);
                llTagFlowLayout.setVisibility(View.VISIBLE);
                inputTopText.setText("退回机构");
                result.setHint("退回原因");
                tvYuanyin.setText("退回原因(非必选,可多选):");
                tvQita.setText("其他 (选填) :");
                tvZhushi.setText("注：退回时，错误原因、其他，至少完善其中1项，方可退回。");
                updataRetreatReason();
                break;
            case "签收驳回":
                llTagFlowLayout.setVisibility(View.GONE);
                llJianyijiage.setVisibility(View.GONE);
                inputTopText.setText("签收驳回");
                result.setHint("签收驳回原因");
                tvYuanyin.setText("签收驳回原因");
                tvZhushi.setVisibility(View.GONE);
                tvQita.setVisibility(View.GONE);
                break;
            case "审核驳回":
                tvZhushi.setVisibility(View.VISIBLE);
                tvQita.setVisibility(View.VISIBLE);
                llJianyijiage.setVisibility(View.VISIBLE);
                llTagFlowLayout.setVisibility(View.VISIBLE);
                inputTopText.setText("审核驳回");
                result.setHint("审核驳回原因");
                tvYuanyin.setText("驳回原因(非必选,可多选):");
                tvQita.setText(" 其他(非必填) :");
                tvZhushi.setText("注：驳回时，信息错误、建议价格、其他，至少完善其中1项，方可驳回。");
                upDataRejectReason();
                break;
            case "专业线下退回":
                llTagFlowLayout.setVisibility(View.GONE);
                llJianyijiage.setVisibility(View.GONE);
                inputTopText.setText("退回原因");
                result.setHint("退回原因");
                tvYuanyin.setText("退回原因");
                tvZhushi.setVisibility(View.GONE);
                tvQita.setVisibility(View.GONE);
                break;
            default:

                break;
        }
    }

    private void upDataRejectReason() {
        //审核驳回
        List<StatusData.ItemListEntity.RejectReasonEntity.ItemEntity> rejectReasons = statusData.getItemList().getRejectReason().getItem();
        for (int i = 0; i < rejectReasons.size(); i++) {
            reasons.add(rejectReasons.get(i).getValue());
        }
        rejectAdapter = new RejectAdapter(reasons, selectReason, this);
        selectReason.setAdapter(rejectAdapter);
    }

    private void updataRetreatReason() {
        //退回
        List<StatusData.ItemListEntity.RetreatReasonEntity.ItemEntity> retreatReasons = statusData.getItemList().getRetreatReason().getItem();
        for (int i = 0; i < retreatReasons.size(); i++) {
            reasons.add(retreatReasons.get(i).getValue());
        }
        rejectAdapter = new RejectAdapter(reasons, selectReason, this);
        selectReason.setAdapter(rejectAdapter);
    }

    @Override
    public void goBack(View v) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(result.getWindowToken(), 0);
        super.goBack(v);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(result.getWindowToken(), 0);
        finish();
    }

    @OnClick({R.id.tv_right})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_right:
                switch (status) {
                    case "退回":
                        if (checkParams()) {

                            if (TextUtils.isEmpty(result.getText().toString())) {
                                if (!TextUtils.isEmpty(selectReasonStr)) {
                                    selectReasonStr = selectReasonStr.substring(0, selectReasonStr.length() - 1);
                                }
                            }
                            String reson = selectReasonStr + result.getText().toString();
                            sendBack(reson);
                        }
                        break;
                    case "签收驳回":
                        if (TextUtils.isEmpty(result.getText().toString())) {
                            Toast.makeText(this, "请填写驳回原因！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        receiveBack(result.getText().toString());
                        break;
                    case "审核驳回":
                        if (checkParams()) {
                            if (TextUtils.isEmpty(result.getText().toString())) {
                                if (!TextUtils.isEmpty(selectReasonStr)) {
                                    selectReasonStr = selectReasonStr.substring(0, selectReasonStr.length() - 1);
                                }
                            }
                            String reson = priceReson + selectReasonStr + result.getText().toString();
                            Logger.e(reson);
                            verifyBack(reson);
                        }
                        break;
                    case "专业线下退回":
                        if (TextUtils.isEmpty(result.getText().toString())) {
                            Toast.makeText(this, "请填退回原因！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        ZyverifyBack(result.getText().toString());
                        break;
                    default:

                        break;
                }

                break;
            default:

                break;
        }
    }

    //校验参数规则
    private boolean checkParams() {
//        ArrayList<Integer> selects = (ArrayList) selectReason.getSelectedList();
        HashSet<Integer> selects = (HashSet) selectReason.getSelectedList();
        String strC2B = edC2b.getText().toString();//收车价
        String strB2C = edB2c.getText().toString();//售车价
        if (selects.size() > 0) {  //选中的有原因
            for (int i : selects) {
                selectReasonStr = selectReasonStr + reasons.get(i) + ";";
            }
        }
        if (!TextUtils.isEmpty(result.getText().toString().trim()) || selects.size() > 0
                || !TextUtils.isEmpty(strC2B.trim())
                || !TextUtils.isEmpty(strB2C.trim())) {
            try {
                if (details != null && !TextUtils.isEmpty(strC2B.trim())) {
                    if (StringUtils.getIntPrice(details.getSalePriceC2B()) > StringUtils.getIntPrice(strC2B)) {//建议收车价格比较评估价格小
                        priceReson = "收车价偏高 ";
                    } else if (StringUtils.getIntPrice(details.getSalePriceC2B()) < StringUtils.getIntPrice(strC2B)) {
                        priceReson = "收车价偏低 ";
                    }
                }
                if (details != null && !TextUtils.isEmpty(strB2C.trim())) {
                    if (StringUtils.getIntPrice(details.getSalePriceB2C()) > StringUtils.getIntPrice(strB2C)) {//建议售车价格比评估价格小
                        priceReson = priceReson + "售车价偏高 ";
                    } else if (StringUtils.getIntPrice(details.getSalePriceB2C()) < StringUtils.getIntPrice(strB2C)) {
                        priceReson = priceReson + "售车价偏低 ";
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                priceReson = "";
            }
            return true;
        } else {
            Toast.makeText(RejectActivity.this, "请选择或输入原因", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    private void ZyverifyBack(String reason) {
        //专业线下退回
        showDialog();
        taskViewPresenter.ZyOperationData(appContext.getUser().getUserId() + "", "TuiHui", id, reason, "");
    }

    private void verifyBack(String reason) {
        showDialog();
        //审核驳回
        operationPresenter.OperationBack("shenpibohui", String.valueOf(appContext.getUser().getUserId()), edB2c.getText().toString(), edC2b.getText().toString(), reason, id);
    }

    private void receiveBack(String reason) {
        showDialog();
        //签收驳回
        operationPresenter.OperationData("qianshoubohui", id, reason, "", "", String.valueOf(appContext.getUser().getUserId()));
    }

    private void sendBack(String reason) {
        showDialog();
        //线上退回
        operationPresenter.OperationBack("tuihui", String.valueOf(appContext.getUser().getUserId()), "", "", reason, id);
    }

    @Override
    public void showError(String error) {
        dismissDialog();
        Toast.makeText(this, Constant.errr_net, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showresult(SuccessData result) {
        dismissDialog();
        if (result.getStatus() == 100) {
            LocalData.isRefresh = true;
            try {
                AppManager.getAppManager().finishActivity(FastOnlineCheckActivity1.class);
                AppManager.getAppManager().finishActivity(TaskDetailActivity.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //操作成功
            finish();
        }
        Toast.makeText(this, result.getMsg(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showViewDatas(TaskViewData datas) {

    }

    /*   @Override
       public void DeleteDataStadus(SuccessData datas) {
       }*/
    @Override
    public void OperationDatas(SuccessData datas) {
        //专业线下退回联网结果
        dismissDialog();
        if (datas.getStatus() == 100) {
            AppManager.getAppManager().finishActivity(TaskViewActivity.class);
            ActivityHelp.startActivity(RejectActivity.this, OfflineDetectionActivity.class);
            Toast.makeText(this, "专业线下退回成功", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(this, "专业线下退回失败" + datas.getStatus() + "", Toast.LENGTH_SHORT).show();
        }
    }


}
